<?php

namespace app\api\controller;

use app\api\library\Err;
use think\Request;
use app\common\controller\ApiController;
use think\Db;

/**
 * 场次接口
 */
class Scene extends ApiController
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $tableName = 'scene';
    protected $appointmentTableName = 'appointment';
    protected $fields = '';
    protected $fieldsExcept = false;
    protected $onlySelf = false;
    protected $orderBy = 'date desc, starttime desc';
    // deletetime 为null
    protected $conditions = ['deletetime' => null];

    protected function processData($method, $data)
    {
        if ($method === 'beforeSave') {
            // 用户group_id为2时是管理员         
            if (!$this->isAdmin()) {
                $this->fail("您没有权限进行此操作", 403, Err::UNAUTHENTICATED);
            }
            $data['current_people'] = 0;
            $data['createtime'] = time();
        } else if ($method === 'afterList') {
        } else if ($method === 'beforeList') {
        }

        return $data;
    }

    private function isAdmin()
    {
        $groupId = $this->auth->getUserinfo()['group_id'];
        return $groupId == 2;
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        if (!$this->isAdmin()) {
            $this->fail("您没有权限进行此操作", 403, Err::UNAUTHENTICATED);
        }
        $data = $request->param();
        $data['updatetime'] = time();
        Db::name($this->tableName)->where('id', $id)->update($data);
        return $this->success('', ["id" => $id]);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if (!$this->isAdmin()) {
            $this->fail("您没有权限进行此操作", 403, Err::UNAUTHENTICATED);
        }

        // 逻辑删除
        $data = ['deletetime' => time()];
        Db::name($this->tableName)->where('id', $id)->update($data);
        return $this->success('', ["id" => $id]);
    }

    /**
     * 开放预约列表的接口
     * @return \think\Response
     */
    public function open()
    {
        // 中午12点前只开放当天没结束的场次，12点后再开放第二天的场次
        $userId = $this->auth->getUser()->id;
        $midtime = strtotime(date('Y-m-d') . ' 12:00:00');
        $currtime = time();
        $today = date('Y-m-d');
        $tomorrow = date('Y-m-d', strtotime('+1 day'));

        list($start, $limit) = $this->paging();
        $query = Db::name($this->tableName)->where('deletetime', null);
        if ($currtime <= $midtime) {
            $query = $query->where('date', '=', $today);
        } else {
            $query = $query->where('date', '>=', $today)
                ->where('date', '<=', $tomorrow);
        }

        $query = $query->order('date asc, starttime asc');
        $query = $query->limit($start, $limit);
        $data = $query->select();
        $newData = [];
        foreach ($data as $row) {
            if ($row['date'] == $today && time() >= strtotime($row['date'] . ' ' . $row['endtime'])) {
                continue;
            }
            // 用户是否已预约该场次
            $appointment = Db::name($this->appointmentTableName)
                ->where('scene_id', $row['id'])
                ->where('user_id', $userId)
                ->select();
            $row['is_appointmnet'] = $appointment ? 1 : 0;
            $newData[] = $row;
        }

        return $this->success('', $newData);
    }

    /**
     * 场次数据统计
     * @return \think\Response
     */
    public function stat()
    {
        list($start, $limit) = $this->paging();
        $query = Db::name($this->tableName)
            ->where('date', '<=', date('Y-m-d'))
            ->where('deletetime', null)
            ->field('date, COUNT(*) as scene_count, SUM(max_people) as max_people, SUM(current_people) as current_people')
            ->group('date')
            ->order('date desc');
        $query = $query->limit($start, $limit);
        $data = $query->select();
        $ret = [];
        foreach ($data as $row) {
            $row = array_merge($row, $this->totalStat($row['date']));
            $row['avg_people'] = floor($row['is_used'] / $row['scene_count']);
            $ret[] = $row;
        }
        return $this->success('', $ret);
    }

    private function totalStat($date)
    {
        $data = Db::query("SELECT IFNULL(SUM(IFNULL(a.is_used, 0)), 0) as is_used FROM `fa_appointment` as a LEFT JOIN fa_scene AS b ON a.scene_id = b.id WHERE b.date = ?", [$date]);
        return $data[0];
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $this->conditions = [];
        $data = $this->buildQuery()->find($id);
        if (!$data) {
            $this->fail('No data is avaliable', 404);
        }
        return $this->res($data);
    }
}
